package com.wqiuqiu.gulimall.secdkill.interceptor;

import com.wqiuqiu.common.constant.RedisConstant;
import com.wqiuqiu.common.to.login.MemberResponseTo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;


@Component
public class SecdkillInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //拦截器放行
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HashSet<String> matchs = new HashSet<>();
        matchs.add("/{skuId}");
        for (String match : matchs) {
            if (antPathMatcher.match(match,uri))
                return true;
        }

        HttpSession session = request.getSession();
        MemberResponseTo attribute = (MemberResponseTo) session.getAttribute(RedisConstant.SESSIONNAME);
        if (attribute != null){
            //用户已经登录
            threadLocal.set(attribute);
            return true;
        }else {
            //没有登录
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }

    }
}
